// 要求设计 LazyMan 类，实现以下功能。
// LazyMan('Tony');// Hi I am Tony
// LazyMan('Tony').sleep(10).eat('lunch');// Hi I am Tony// 等待了 10 秒...// I am eating lunch
// LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');// Hi I am Tony// I am eating lunch// 等待了 10 秒...// I am eating diner
// LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');// Hi I am Tony// 等待了 5 秒...// I am eating lunch// I am eating dinner//等待了 10 秒...// I am eating junk food
class LazyManCls {
    constructor(name) {
        console.log(`Hi I am ${name}!`);
        this.tasks = [];
        this.start();
    }

    /**
     * 启动任务，需要加延时
     */
    start() {
        setTimeout(this.runTask.bind(this));
    }

    async runTask() {
        for (let func of this.tasks) {
            await func();
        }
        // 以下是不使用async/await的方法
        // var p = this.tasks.shift();
        // if (!p) {
        //     return;
        // }
        // Promise.resolve(p()).then(() => {
        //     this.runTask();
        // });
    }

    sleepAction(time) {
        return new Promise((resolve) => {
            setTimeout(function () {
                console.log(`等待了${time}秒...`);
                resolve();
            }, time * 1000);
        });
    }

    sleep(time) {
        this.tasks.push(() => {
            return this.sleepAction(time);
        });
        return this;
    }

    sleepFirst(time) {
        this.tasks.unshift(() => {
            return this.sleepAction(time);
        });
        return this;
    }

    eatAction(food) {
        console.log(`I am eating ${food}.`);
    }

    eat(food) {
        this.tasks.push(() => {
            return this.eatAction(food);
        });
        return this;
    }
}

function LazyMan(name) {
    return new LazyManCls(name);
}

// LazyMan('Tony');
// LazyMan('Tony').sleep(10).eat('lunch');
// LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
